package factorytest.iflytek.com.einkiflytekfactorytest.engineerui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import factorytest.iflytek.com.einkiflytekfactorytest.BuildConfig;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.common.BatteryInfo;
import factorytest.iflytek.com.einkiflytekfactorytest.config.EinkProperty;
import factorytest.iflytek.com.einkiflytekfactorytest.config.NVRomKeys;
import factorytest.iflytek.com.einkiflytekfactorytest.config.PCCommand;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;
import factorytest.iflytek.com.einkiflytekfactorytest.common.FTUtils;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.SystemPropertyUtil;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.UsefulUtils;


public class EngineerMainActivity extends Activity implements AdapterView.OnItemClickListener {

    private final static String TAG = "MainActivity";
    private GridView gridlist;
    private List<EngineerTestItemsEnum> itemsEnumList = new ArrayList<>();


    private Context mContext;
    private TextView txtDesc;
    private TextView txtAgingResult;

    private TextView txtBatteryInfo;

    private MyGridAdapter myGridAdapter;

    private BatteryInfo batteryInfo;

    @SuppressLint("StringFormatInvalid")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        setContentView(R.layout.activity_main_engineer_test);

        mContext = this;

        batteryInfo = new BatteryInfo(this);


        gridlist = (GridView) findViewById(R.id.grid_list);
        gridlist.setOnItemClickListener(this);

        itemsEnumList.clear();

        Collections.sort(itemsEnumList, new Comparator<EngineerTestItemsEnum>() {
            @Override
            public int compare(EngineerTestItemsEnum o1, EngineerTestItemsEnum o2) {
                return o1.getIdentify() - o2.getIdentify();
            }
        });

        myGridAdapter = new MyGridAdapter(mContext, -1, itemsEnumList);
        gridlist.setAdapter(myGridAdapter);

        txtDesc = (TextView) findViewById(R.id.txtDesc);
        txtAgingResult = (TextView) findViewById(R.id.txtAgingResult);

        TextView txtVersion = (TextView) findViewById(R.id.txtVersion);
        txtVersion.setText(getString(R.string.app_version, UsefulUtils.getAppVersion(mContext) + "-" + BuildConfig.BUILD_TYPE));

        TextView txtSerialno = (TextView) findViewById(R.id.txtSerialno);
        txtSerialno.setText(getString(R.string.serialno, SystemPropertyUtil.getSystemProperty("sys.serialno")));

        TextView txtRamRomSize = (TextView) findViewById(R.id.txtRamRomSize);
        txtRamRomSize.setText(getString(R.string.ram_and_rom, UsefulUtils.getRamNominalSize(), UsefulUtils.getRomNominalSize()));

        txtBatteryInfo = (TextView) findViewById(R.id.txtBatteryInfo);

        updateItemByAfterAging(true);

        FTUtils.startFTFloat(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (FTUtils.isEngineerTestItemsAllPassed()) {

            txtDesc.setText(R.string.desc_after_aging);
            txtAgingResult.setText(FTUtils.getAgingResultInfo(mContext));

        } else {

            txtDesc.setText(R.string.desc_before_aging);
            txtAgingResult.setText("");

        }

        batteryInfo.setOnBatteryChangedListener(onBatteryChangedListener);
        batteryInfo.startMonitor();

        if (FTUtils.isInAgingTest(mContext)) {
            DebugLog.e("start aging test activity.");
            EngineerTestItemsEnum itemsEnum = EngineerTestItemsEnum.aging;
            Intent intent = new Intent(mContext, itemsEnum.getItemClass());
            startActivityForResult(intent, itemsEnum.getIdentify());
        }

        if (PCCommand.isFromPCBroadcast(mContext)) {
            myGridAdapter.notifyDataSetChanged();
            PCCommand.clearFromPCBroadcast(mContext);
            updateItemByAfterAging();
        }

        EinkProperty.setEinkFTTestAllResultPassed(FTUtils.isFTPassed());

    }

    @Override
    protected void onPause() {
        super.onPause();
        batteryInfo.setOnBatteryChangedListener(null);
        batteryInfo.stopMonitor();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DebugLog.e( "onActivityResult requestCode = " + requestCode + ", resultCode = " + resultCode);

        EngineerTestItemsEnum itemsEnum = EngineerTestItemsEnum.getItemEnumByIdentify(requestCode);

        if (itemsEnum == null) {
            return;
        }
        String result = getString(R.string.test_result_unknown);
        if (resultCode == RESULT_OK) {
            result = getString(R.string.test_result_pass);
        } else if (resultCode == RESULT_CANCELED) {
            result = getString(R.string.test_result_fail);
        }

        EngineerTestItemsEnum agingItemsEnum = EngineerTestItemsEnum.aging;

        DebugLog.e("itemsEnum = " + (itemsEnum));

        if (itemsEnum != agingItemsEnum && agingItemsEnum.isPassed(mContext)) {

            itemsEnum.setResultForAfterAging(mContext, result);

        } else {

            itemsEnum.setResult(mContext, result);

        }

        if (resultCode == RESULT_OK && agingItemsEnum == itemsEnum) {
            itemsEnum.setResultForLog(mContext, FTUtils.getAgingResultInfo(mContext));
        }

        updateItemByAfterAging();

        myGridAdapter.notifyDataSetChanged();

    }

    private void updateItemByAfterAging() {

        updateItemByAfterAging(false);
    }

    private void updateItemByAfterAging(boolean force) {

        if (FTUtils.isEngineerTestItemsAllPassed() ) {

            if (!myGridAdapter.isUseResultOfAfterAging() || force) {
                itemsEnumList.clear();

                myGridAdapter.setUseResultOfAfterAging(true);

                for (EngineerTestItemsEnum item : EngineerTestItemsEnum.values()) {

                    if (item.isKeepTestAfterAging()) {
                        itemsEnumList.add(item);
                    }
                }
            }

        } else {

            if (myGridAdapter.isUseResultOfAfterAging() || force) {
                itemsEnumList.clear();

                myGridAdapter.setUseResultOfAfterAging(false);

                itemsEnumList.addAll(Arrays.asList(EngineerTestItemsEnum.values()));

            }

        }
    }

///////////////////////////////////////////////////////////////

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EngineerTestItemsEnum itemsEnum = myGridAdapter.getItem(position);
        if (itemsEnum == null || itemsEnum.getItemClass() == null) {
            return;
        }

        if (itemsEnum == EngineerTestItemsEnum.aging && (!FTUtils.isEngineerTestItemsAllPassedExcludeAging())) {
            Toast.makeText(mContext, R.string.aging_item_clicked_while_others_not_tested, Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(mContext, itemsEnum.getItemClass());
        if (itemsEnum.getIdentify() == NVRomKeys.ID_ELECTRIC_TP) {
            intent.putExtra("etp",true);
        }
        startActivityForResult(intent, itemsEnum.getIdentify());

    }

    private class MyGridAdapter extends ArrayAdapter<EngineerTestItemsEnum> {

        private boolean useResultOfAfterAging = false;
        public MyGridAdapter(@NonNull Context context, int resource, @NonNull List<EngineerTestItemsEnum> objects) {
            super(context, resource, objects);
            useResultOfAfterAging = false;
        }

        public boolean isUseResultOfAfterAging() {
            return useResultOfAfterAging;
        }

        public void setUseResultOfAfterAging(boolean useResultOfAfterAging) {
            this.useResultOfAfterAging = useResultOfAfterAging;
        }

        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull final ViewGroup parent) {

            ViewHolder holder = null;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            }

            if (holder == null) {
                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_test, null);
                holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
                holder.txtStatus = (TextView) convertView.findViewById(R.id.txtStatus);
                convertView.setTag(holder);
            }

            final EngineerTestItemsEnum itemsEnum = getItem(position);

            if (itemsEnum != null) {
                holder.txtName.setText(itemsEnum.getNameResId());
                if (isUseResultOfAfterAging()) {
                    holder.txtStatus.setText(itemsEnum.getResultForAfterAging(getContext()));

                } else {
                    holder.txtStatus.setText(itemsEnum.getResult(getContext()));
                }
            }

            return convertView;
        }

    }

    private final class ViewHolder {
        TextView txtName;
        TextView txtStatus;
    }

    private BatteryInfo.OnBatteryChangedListener onBatteryChangedListener =
            new BatteryInfo.OnBatteryChangedListener() {
                @Override
                public void onBatteryChangedListener(BatteryInfo info) {

                    String infoString = mContext.getString(R.string.aging_hardware_battery_info,
                            info.getBatteryVoltage(),
                            info.getBatteryLevel(),
                            info.getBatteryStatusString(),
                            info.getBatteryCurrent_mA());


                    txtBatteryInfo.setText(infoString);
                }
            };

}
